package com.foreveross.crawl.adapter.sub.impl20140402.v3;

/**
 * 美国达美航空（DL）适配器
 * 
*/

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.common.util.RandomBrowserVersion;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Maps;

public class DLAdapter extends AbstractAdapter {

	private HttpClient httpClient;
	private String useAgent;
	private String httpSessionId;
	private String scriptSessionId;
	private String currentSessionCheckSum;
	public DLAdapter(TaskModel taskQueue) {
		super(taskQueue);
		useAgent = RandomBrowserVersion.getBV().getUserAgent();
	}
	
	public int BACK_1=1;
	
	private static Map<String,String> monthsMap = Maps.newHashMap();
			{
				monthsMap.put("01","Jan");
				monthsMap.put("02","Feb");
				monthsMap.put("03","Mar");
				monthsMap.put("04","Apr");
				monthsMap.put("05","Map");
				monthsMap.put("06","Jun");
				monthsMap.put("07","Jul");
				monthsMap.put("08","Aug");
				monthsMap.put("09","Sep");
				monthsMap.put("10","Oct");
				monthsMap.put("11","Nov");
				monthsMap.put("12","Dec");
			};
	
	@Override
	public List<Object> paraseToVo(Object obj) throws Exception {
		switch (super.getRouteType()) {
		case INTERNATIONAL_ROUND:
			return paraseToVoDI(obj);//国际往返
		case INTERNATIONAL_ONEWAY:
			return paraseToVoDI(obj);//国际单程（头等/经济）
		case DOMESTIC_ONEWAYTRIP:
			return null;
		}
		return null;
	}

	/**
	 * 国际往返——适配器
	 */	
	private List<Object> paraseToVoDI(Object fetchObject) throws Exception {
		

		return null;
	}
	
	@Override
	public String getUrl() throws Exception {
		return "http://zh.delta.com/air-shopping/findFlights.action";
	}

	@Override
	public Object fetch(String url) throws Exception {
		//1、进入页面获得一些参数，同时传递查询参数
		this.fetchEnterUrl();
		//2、获得去程的页面
		this.fetchGoTrip();
		return null;
	}
	/**
	 * 进入的第一个页面
	 * <p>带查询条件传递给后台
	 * @throws Exception
	 */
	private void fetchEnterUrl() throws Exception{
//		WebRequest request = new WebRequest(new URL("http://zh.delta.com/air-shopping/findFlights.action"),HttpMethod.POST);
//		request.setCharset("utf-8");
//		request.setRequestParameters(Arrays.asList(new NameValuePair("tripType", "ROUND_TRIP"),
//				new NameValuePair("showMUUpgrade", "on"),
//				new NameValuePair("searchType", "simple"),
//				new NameValuePair("returnTime", "AT"),
//				new NameValuePair("returnDate", DateUtil.formatDate(DateUtils.parseDate(taskQueue.getReturnGrabDate(), "yyyy-MM-dd"), "MM/dd/yyyy")),
//				new NameValuePair("preferItinId", ""),
//				new NameValuePair("paxCount", "1"),
//				new NameValuePair("originCity", taskQueue.getFromCity()),
//				new NameValuePair("MUUpgrade", "on"),
//				new NameValuePair("flexMainRTRTravelDate", "off"),
//				new NameValuePair("fareBundle", "B5-Coach"),
//				new NameValuePair("dl", "y"),
//				new NameValuePair("dispatchMethod", "findFlights"),
//				new NameValuePair("directServiceOnly", "off"),
//				new NameValuePair("destinationCity", taskQueue.getToCity()),
//				new NameValuePair("departureTime", "AT"),
//				new NameValuePair("departureDate", DateUtil.formatDate(DateUtils.parseDate(taskQueue.getFlightDate(), "yyyy-MM-dd"), "MM/dd/yyyy")),
//				new NameValuePair("deltaOnly", "off"),
//				new NameValuePair("bundled", "off"),
//				new NameValuePair("bookingPostVerify", "RTR_YES"),
//				new NameValuePair("__checkbox_upgradeRequest", "true"),
//				new NameValuePair("__checkbox_smTravelling", "true"),
//				new NameValuePair("__checkbox_datesFlexible", "true"),
//				new NameValuePair("__checkbox_awardTravel", "true")));
//
//		WebClient client = super.getWebClient();
//		client.addRequestHeader("Host", "zh.delta.com");
//		client.addRequestHeader("User-Agent",useAgent);
//		client.addRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//		client.addRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
//		client.addRequestHeader("Referer","http://zh.delta.com/");
//		HtmlPage goTripPage = client.getPage(request);
		//Thread.sleep(60000l);
//		FileUtils.write(new File("e:/mytemp/dl.html"), goTripPage.asXml());
		PostMethod httpPost = null;
		GetMethod httpGet = null;
		org.apache.commons.httpclient.Header cookiesH = null;
		String page = null;
		try{
			logger.info("达美航空开始请求查询.....");
		    httpClient = this.getComHttpCient();
			httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
			httpPost = new PostMethod("http://zh.delta.com/air-shopping/findFlights.action");
			httpPost.addParameter("tripType", "ROUND_TRIP");
			httpPost.addParameter("showMUUpgrade", "on");
			httpPost.addParameter("searchType", "simple");
			httpPost.addParameter("returnTime", "AT");
			httpPost.addParameter("returnDate", DateUtil.formatDate(DateUtils.parseDate(taskQueue.getReturnGrabDate(), "yyyy-MM-dd"), "MM/dd/yyyy"));
			httpPost.addParameter("preferItinId", "");
			httpPost.addParameter("paxCount", "1");
			httpPost.addParameter("originCity", taskQueue.getFromCity());
			httpPost.addParameter("MUUpgrade", "on");
			httpPost.addParameter("flexMainRTRTravelDate", "off");
			httpPost.addParameter("fareBundle", "B5-Coach");
			httpPost.addParameter("dl", "y");
			httpPost.addParameter("dispatchMethod", "findFlights");
			httpPost.addParameter("directServiceOnly", "off");
			httpPost.addParameter("destinationCity", taskQueue.getToCity());
			httpPost.addParameter("departureTime", "AT");
			httpPost.addParameter("departureDate", DateUtil.formatDate(DateUtils.parseDate(taskQueue.getFlightDate(), "yyyy-MM-dd"), "MM/dd/yyyy"));
			httpPost.addParameter("deltaOnly", "off");
			httpPost.addParameter("bundled", "off");
			httpPost.addParameter("bookingPostVerify", "RTR_YES");
			httpPost.addParameter("__checkbox_upgradeRequest", "true");
			httpPost.addParameter("__checkbox_smTravelling", "true");
			httpPost.addParameter("__checkbox_datesFlexible", "true");
			httpPost.addParameter("__checkbox_awardTravel", "true");
			httpPost.setRequestHeader("Host", "zh.delta.com");
			httpPost.setRequestHeader("User-Agent",useAgent);
			httpPost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpPost.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			httpPost.setRequestHeader("Referer","http://zh.delta.com/");
			httpClient.executeMethod(httpPost);
			page = httpPost.getResponseBodyAsString();
			super.appendPageContents(page);//保存源网页数据
			FileUtils.write(new File("e:/mytemp/dl-first.html"), page);
			cookiesH = httpPost.getResponseHeader("Set-Cookie");
			httpSessionId = RegHtmlUtil.regStr(cookiesH.getValue(),"JSESSIONID=(\\w*\\:\\w*\\W*\\w*)");
			currentSessionCheckSum=RegHtmlUtil.regStr(page,"currentSessionCheckSum\\s*?\\=\\s*?\\W*(\\w*)\\W*");
			httpGet = new GetMethod("http://zh.delta.com/sdcontent/dlhome/gzip_1698632109/shared/jawr/20140619/js/1352522744000/dwr.js");
			httpClient.executeMethod(httpGet);
			page = httpGet.getResponseBodyAsString();
			super.appendPageContents(page);//保存源网页数据
			scriptSessionId = RegHtmlUtil.regStr(page,"dwr.engine._origScriptSessionId=\"(\\w*)\"");
			logger.info(String.format("获得的隐藏参数httpSessionId=%s,scriptSessionId=%s,currentSessionCheckSum=%s",
									httpSessionId,scriptSessionId,currentSessionCheckSum));
		}finally{
			httpPost = null;
			cookiesH = null;
			page = null;
			httpGet = null;
		}
	}
	/**
	 * 获得去程数据
	 * @throws IOException 
	 */
	private void fetchGoTrip() throws IOException{
		PostMethod httpPost = null;
		String resultPage =  null;
		try{
			logger.info("达美航空开始请求去程数据...");
//			httpPost = new PostMethod("http://zh.delta.com/databroker/bcdata.action");
//			httpPost.setRequestHeader("Host", "zh.delta.com");
//			httpPost.setRequestHeader("User-Agent",useAgent);
//			httpPost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//			httpPost.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
//			httpPost.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//			httpPost.setRequestHeader("Referer","http://zh.delta.com/air-shopping/findFlights.action");
//			httpClient.executeMethod(httpPost);
//			resultPage = httpPost.getResponseBodyAsString();
//			super.appendPageContents(resultPage);//保存源网页数据
//			System.out.println(resultPage);
			httpPost = new PostMethod("http://zh.delta.com/air-shopping/dwr/call/plaincall/SearchFlightResultsDWR.searchResults.dwr");
			httpPost.addParameter("callCount", "1");
			httpPost.addParameter("page", "/air-shopping/findFlights.action");
			httpPost.addParameter("httpSessionId", httpSessionId);
			httpPost.addParameter("scriptSessionId", scriptSessionId);
			httpPost.addParameter("c0-scriptName", "SearchFlightResultsDWR");
			httpPost.addParameter("c0-methodName", "searchResults");
			httpPost.addParameter("c0-id", "0");
			httpPost.addParameter("c0-param0", "string:"+currentSessionCheckSum);
			httpPost.addParameter("c0-e1", "string:deltaBestMatch");
			httpPost.addParameter("c0-e2", "boolean:false");
			httpPost.addParameter("c0-param1", "Array:[reference:c0-e1,reference:c0-e2]");
			httpPost.addParameter("c0-param2", "boolean:false");
			httpPost.addParameter("c0-param3", "boolean:false");
			httpPost.addParameter("batchId", "0");
			httpPost.setRequestHeader("Host", "zh.delta.com");
			httpPost.setRequestHeader("User-Agent",useAgent);
			httpPost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpPost.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			httpPost.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			httpPost.setRequestHeader("Referer","http://zh.delta.com/air-shopping/findFlights.action");
			httpClient.executeMethod(httpPost);
			resultPage = httpPost.getResponseBodyAsString();
			super.appendPageContents(resultPage);//保存源网页数据
			FileUtils.write(new File("e:/mytemp/dl.html"), resultPage);
		}finally{
			httpPost = null;
			resultPage = null;
		}
	}
	/**
	 * 获得回程数据
	 */
	private void fetchReturnTrip(){
		
	}


	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		return true;
	}
	
	
	
	private String getUrlDouble() throws Exception {
		//组装适配器地址
		StringBuffer url=new StringBuffer("http://zh.delta.com/booking/findFlights.do?");
		url.append("dispatchMethod=findFlights");
		url.append("&redirectFromPolaris=Y");
		url.append("&cabinClassOption=cabin");
		url.append("&disableQuickPrice=false");
		url.append("&departureDate[1]="+taskQueue.getReturnGrabDate().substring(5,7)+"%2F"+taskQueue.getReturnGrabDate().substring(8)+"%2F"+taskQueue.getReturnGrabDate().substring(0,4));
		url.append("&departureDate[0]="+taskQueue.getFlightDate().substring(5,7)+"%2F"+taskQueue.getFlightDate().substring(8)+"%2F"+taskQueue.getFlightDate().substring(0,4));
		url.append("&departureCity[1]="+super.taskQueue.getToCity());
		url.append("&paxCount=1");
		url.append("&departureCity[0]="+super.taskQueue.getFromCity());
		url.append("&departureTimeOptions[1]=AT");
		url.append("&departureTimeOptions[0]=AT");
		url.append("&fareCategory=false");
		url.append("&price_schedule=price");
		url.append("&destinationCity[1]="+super.taskQueue.getFromCity());
		url.append("&destinationCity[0]="+super.taskQueue.getToCity());
		url.append("&departureDayOptions[1]="+super.taskQueue.getReturnGrabDate().substring(8));
		url.append("&departureDayOptions[0]="+super.taskQueue.getFlightDate().substring(8));
		url.append("&departureMonthOptions[1]="+monthsMap.get(super.taskQueue.getReturnGrabDate().substring(5,7)));
		url.append("&flexSearchOption=exact");
		url.append("&departureMonthOptions[0]="+monthsMap.get(super.taskQueue.getFlightDate().substring(5,7)));
		url.append("&cabinFareBundle=B5-Coach&tripType=roundtrip#top");
	//	String str="http://zh.delta.com/booking/findFlights.do?dispatchMethod=findFlights&redirectFromPolaris=Y&cabinClassOption=cabin&disableQuickPrice=false&departureDate[1]=04%2F27%2F2015&departureDate[0]=03%2F24%2F2015&departureCity[1]=FRA&paxCount=1&departureCity[0]=PEK&departureTimeOptions[1]=AT&departureTimeOptions[0]=AT&fareCategory=false&price_schedule=price&destinationCity[1]=PEK&destinationCity[0]=FRA&departureDayOptions[1]=27&departureDayOptions[0]=24&departureMonthOptions[1]=Apr&flexSearchOption=exact&departureMonthOptions[0]=Mar&cabinFareBundle=B5-Coach&tripType=roundtrip#top";
		return url.toString();
	}
	
	/**
	 * 进入页面信息获取（对应的去程航线信息）
	 * URL
	*/
	public String getURL(String hiddenId,String checkSum){
		StringBuffer url=new StringBuffer("http://zh.delta.com/booking/retrieveFlights.do?dispatchMethod=retrieveFlights");
		url.append("&hiddenFieldsId="+hiddenId);
		url.append("&checksum="+checkSum);
		url.append("&tSession="+hiddenId);
		url.append("&UIStatus=P");
		url.append("&ts"+new Date().getTime());
		//url.append("#top");
		return url.toString();
	}
	
	/**
	 * 点击去程信息（经济）
	 * reurn 对应的返回经济回程信息
	 * 
	*/
	public String bEUrl(String hiddenId,String checkSum,String sLeg,String sId){
		StringBuffer url=new StringBuffer("http://zh.delta.com/booking/pricedItineraries.do?dispatchMethod=smloginRefresh");
		url.append("&hiddenFieldsId"+hiddenId);
		url.append("&checksum="+checkSum);
		url.append("&cacheKey="+hiddenId);
		url.append("&selectedLeg="+sLeg);
		url.append("&selectedSegmentId="+sId);
		url.append("&selectedItinSeqNum="+sLeg);
		url.append("&sortBy=null&stopsFilter=null&deptAirportFilter=null&arrAirportFilter=undefined&inFlightAmenityFilter=undefined");		
		return url.toString();
	}
	
	/**
	 * 点击去程商务舱
	 * return 回程商务舱信息
	*/
	public String bBUrl(String hiddenId,String checksum){
		StringBuffer url=new StringBuffer("https://zh.delta.com/booking/retrieveFlights.do?dispatchMethod=retrieveFlights");
		url.append("s&hiddenFieldsId="+hiddenId);
		url.append("&checksum="+checksum);
		url.append("&tSession="+hiddenId);
		url.append("&UIStatus=RetrySchdPath&ts="+new Date().getTime());
		url.append("#top&UnaPrice=Y");
		return url.toString();
	}

}
